package com.jzwl.common.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import com.jzwl.system.base.dao.BaseDAO;
/**
 * 资源源数据定义，即定义某一资源可以被哪些角色访问
 *
 */
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
			 
	private static Map<String, Collection<ConfigAttribute>> resourceMap = null;
	private PathMatcher pathMatcher = new AntPathMatcher();
	
	@Autowired
	private BaseDAO baseDAO;//dao基类，操作数据库

	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	/**
	 * 加载资源与权限的映射关系
	 * @return
	 */
	private Map<String, Collection<ConfigAttribute>> loadResourceMatchAuthority() {
		Map<String, Collection<ConfigAttribute>> map = new HashMap<String, Collection<ConfigAttribute>>();
		// 获取资源权限映射key：url，value：role

		Map<String, String> configs = getResources();
		for (Entry<String, String> entry : configs.entrySet()) {
			Collection<ConfigAttribute> list = new ArrayList<ConfigAttribute>();
			String[] vals = entry.getValue().split(",");
			for (String val : vals) {
				ConfigAttribute config = new SecurityConfig(val);
				list.add(config);
			}
			map.put(entry.getKey(), list);
		}
		return map;
	}

	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		if(resourceMap==null){
			resourceMap = loadResourceMatchAuthority();
		}
		String url = ((FilterInvocation) object).getRequestUrl();
		// logger.info("requestUrl is " + url);

		if (resourceMap == null) {
			loadResourceMatchAuthority();
		}
		// 比较url是否存在
		Iterator<String> ite = resourceMap.keySet().iterator();
		while (ite.hasNext()) {
			String resURL = ite.next();
			if (pathMatcher.match(resURL, url)) {
				return resourceMap.get(resURL);
			}
		}
		return resourceMap.get(url);
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}
	
	/**
	 * 多个角色——五个权限—多个资源
	 * 获取资源权限映射key：url，value：role
	 * @return
	 */
	public Map<String, String> getResources() {
//		String sql = "SELECT ra.authorityId,res.resourceUrl,a.authorityCode FROM plat_authresource ra INNER JOIN plat_resource res ON ra.resourceId = res.resourceId "
//				+ "INNER JOIN plat_authority a ON ra.authorityId = a.authorityId where res.type=1";
		String sql = "select  ar.authorityId,res.resourceUrl from v2_plat_authresource ar LEFT JOIN v2_plat_resource res ON res.resourceId = ar.resourceId ";
		List<Map<String, Object>> list = baseDAO.queryForList(sql);
		Map<String, String> map = new LinkedHashMap<String, String>();
		if(list.size()>0){
			for(int i=0;i<list.size();i++){
				String url = (String)list.get(i).get("resourceUrl");
				String role = list.get(i).get("authorityId").toString();
				if (map.containsKey(url)){
					String value = map.get(url);
					map.put(url, value + "," + role); 
				}else{
					map.put(url, role);
				}
			}
		}
        return map;
	}
}
